<?php


namespace app\portal\controller;

use app\portal\model\ContestCategoryModel;
use app\portal\model\ContestModel;
use app\portal\model\RecycleBinModel;
use cmf\controller\AdminBaseController;
use think\Model;

/**
 * Class AdminContestController
 * @package app\portal\controller
 * @adminMenuRoot(
 *     'name'   =>'比赛管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 40,
 *     'icon'   =>'th',
 *     'remark' =>'比赛管理'
 * )
 */
class AdminContestController extends AdminBaseController
{
    public function index()
    {
        #接收查询条件参数
        $param = $this->request->param();
        # 查询分类id
        $categoryId = $this->request->param('category', 0, 'intval');
        # 获取赛事全部数据
        $contestModel = new ContestModel();
        $data        = $contestModel->adminContestList($param);
        $data->appends($param);
        # 获取赛事分类数据
        $contestCategoryModel = new ContestCategoryModel();
        $categoryTree        = $contestCategoryModel->adminCategoryTree($categoryId);

        $this->assign('apple_start', isset($param['apple_start']) ? $param['apple_start'] : '');
        $this->assign('apple_end', isset($param['apple_end']) ? $param['apple_end'] : '');
        $this->assign('review_start', isset($param['review_start']) ? $param['review_start'] : '');
        $this->assign('review_end', isset($param['review_end']) ? $param['review_end'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('contests', $data->items());
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign('page', $data->render());


        return $this->fetch();
    }

    /**
     * 添加赛事
     */
    public function add() {
        $contestCategory = new ContestCategoryModel();
        $category = $contestCategory->adminCategoryTree();

        $this->assign('category_tree', $category);
        return $this->fetch();
    }

    /**
     * 添加赛事提交
     * @adminMenu(
     *     'name'   => '添加赛事提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加赛事提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            $contestModel = new ContestModel();
            $res = $contestModel->where('title',$data['title'])->find();
            if(!empty($res)) {
                $this->error('赛事名称已存在');
            }
            $contestModel->adminAddContest($data,$data['categories']);
            $this->success('添加成功!', url('AdminContest/edit', ['id' => $contestModel->id]));

        }
    }

    /**
     * 编辑赛事页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit() {
        $id = $this->request->param('id', 0, 'intval');

        $contestModel = new ContestModel();
        $contest            = $contestModel->where('id', $id)->find();
        $contestCategories  = $contest->categories()->alias('a')->column('a.name', 'a.id');
        $contestCategoryIds = implode(',', array_keys($contestCategories));

        $contestCategory = new ContestCategoryModel();
        $category = $contestCategory->adminCategoryTree($contest['category_id']);


        $this->assign('contest', $contest);
        $this->assign('category_tree', $category);
        $this->assign('contest_categories', $contestCategories);
        $this->assign('contest_category_ids', $contestCategoryIds);

        return $this->fetch();
    }

    /**
     * 编辑赛事信息提交
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPost() {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            $contestModel = new ContestModel();

            $findName = $contestModel->where('title',$data['title'])->find();
            if(!empty($findName)) {
                if($findName['id'] != $data['id']) {
                    $this->error('赛事名称重复');
                }
            }

            $contestModel->adminEditContest($data,$data['categories']);

            $this->success('保存成功!');

        }
    }

    /**
     * 赛事删除
     * @adminMenu(
     *     'name'   => '赛事删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '赛事删除',
     *     'param'  => ''
     * )
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delete()
    {
        $param           = $this->request->param();
        $contestModel = new ContestModel();

        if (isset($param['id'])) {
            $id           = $this->request->param('id', 0, 'intval');
            $result       = $contestModel->where('id', $id)->find();
            $data         = [
                'object_id'   => $result['id'],
                'create_time' => time(),
                'table_name'  => 'contest',
                'name'        => $result['title'],
                'user_id'     => cmf_get_current_admin_id()
            ];
            $resultContest = $contestModel
                ->where('id', $id)
                ->update(['delete_time' => time()]);
            if ($resultContest) {
                RecycleBinModel::insert($data);
            }
            $this->success("删除成功！", '');

        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $recycle = $contestModel->where('id', 'in', $ids)->select();
            $result  = $contestModel->where('id', 'in', $ids)->update(['delete_time' => time()]);
            if ($result) {
                foreach ($recycle as $value) {
                    $data = [
                        'object_id'   => $value['id'],
                        'create_time' => time(),
                        'table_name'  => 'contest',
                        'name'        => $value['title'],
                        'user_id'     => cmf_get_current_admin_id()
                    ];
                    RecycleBinModel::insert($data);
                }
                $this->success("删除成功！", '');
            }
        }
    }

    /**
     * 赛事发布
     * @adminMenu(
     *     'name'   => '赛事发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '赛事发布',
     *     'param'  => ''
     * )
     */
    public function publish()
    {
        $param           = $this->request->param();
        $contestModel = new ContestModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            if(count($param['ids']) > 1) {
                $this->error('同一时间只能同时存在1个发布中的赛事！');
            }
            $res = $contestModel->where('status',1)->find();
            if(!empty($res)) {
                $this->error('已有发布中的赛事，请先停用赛事！');
            }
            $ids = $this->request->param('ids/a');
            $contestModel->where('id', 'in', $ids)->update(['status' => 1]);
            $this->success("发布成功！", '');
        }

        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $contestModel->where('id', 'in', $ids)->update(['status' => 0]);
            $this->success("取消发布成功！", '');
        }

    }
}